# Create your views here.

from django.http import Http404
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework.pagination import PageNumberPagination
from rest_framework import filters

from .models import Student
from .serializers import StudentSerializer


class GoodsPagination(PageNumberPagination):
    """
    商品自定义的分页
    """
    page_size = 10  # 设置单页的量 前端可以通过提交 page_size 参数来修改，这里只是个默认值
    max_page_size = 100  # 设置单页最大值
    page_size_query_param = 'page_size'  # 自定义每页数量请求参数
    page_query_param = "current_page"  # 自定义页数请求参数


class StudentView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):

    serializer_class = StudentSerializer

    pagination_class = GoodsPagination  # 调用自定义的分页

    filter_backends = (filters.SearchFilter,)
    search_fields = ('name',)

    def get(self, request, *args, **kwargs):
        print('-----------------')
        print('当前用户:', request.user)
        print('-----------------')
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_queryset(self):
        student_name = self.request.query_params.get("student_name")
        if student_name:
            return Student.objects.filter(name=student_name)
        else:
            return Student.objects.all()
